# -*- coding: UTF-8      -*
from flask import Flask,jsonify,render_template,request,escape,redirect
import urllib
import urllib.request
import sys
import ssl
import json
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SECRET_KEY'] = 'image'

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://zhuang123:NUEST0315@zhuang123.mysql.pythonanywhere-services.com/zhuang123$zjw'

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_name = db.Column(db.String(20))
    password = db.Column(db.String(20))


with app.app_context():
    db.create_all()
# 调用日志记录函数
import requests
def log_request(req:'flask_request',res:str)->None:
	with open('view.log','a') as log:
		print(req.form,req.remote_addr,req.user_agent,res,file=log,sep='|')
def get_access_token():
	host="https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=Pvu0w2rzV8Cib0yGwQHYPKbt&client_secret=DLbj5OeBeC6kGVv51MQAuBYvbKUyl7Dg"
	response = requests.get(host)

	if response:
		access_token = response.json()['access_token']
		return access_token
	else:
		return None
import json

# 进入网页的首页，数据返回首页.html
@app.route('/')
def entry_page() -> 'html':
	return render_template('shouye01.html',the_title='向日葵语言识别系统')

@app.route('/summary',methods=["GET","POST"])
def summary() -> 'html':
	if request.method=="POST":
		title=request.form.get("title")
		content=request.form.get("content")
		acccess_token=get_access_token()
		url="https://aip.baidubce.com/rpc/2.0/nlp/v1/news_summary?charset=UTF-8&access_token="+acccess_token
		body={
			"content": content,
			"max_summary_len": 150
		}
		if title is not  None and title!="":
			body["title"]=title
		Header={"Content-Type":"application/json"}
		response=requests.post(url,json=body,headers=Header)
		content=json.loads(response.text)["summary"]
		log_request(request,response.text)
		return render_template('result_summary.html', the_title='新闻摘要',summary=content,)

	return render_template('pushCategorry.html',the_title='新闻摘要',desction="请在下方输入一篇文章（含标题），生成摘要")
@app.route('/category',methods=["GET","POST"])
def category() -> 'html':
	if request.method=="POST":
		title=request.form.get("title")
		content=request.form.get("content")
		if title is   None or title=="":
			return render_template('pushCategorry.html', the_title='文章分类', desction="请输入一篇文章（含标题），为文章选择分类模块.",msg="请输入标题")
		if content is   None or content=="":
			return render_template('pushCategorry.html', the_title='文章分类', desction="请输入一篇文章（含标题），为文章选择分类模块.",msg="请输入标题")

		acccess_token=get_access_token()
		url="https://aip.baidubce.com/rpc/2.0/nlp/v1/topic?charset=UTF-8&access_token="+acccess_token
		body={
			"title":title,
			"content": content,
		}
		if title is not  None or title!="":
			body["title"]=title
		Header={"Content-Type":"application/json"}
		response=requests.post(url,json=body,headers=Header)
		log_request(request,response.text)

		category=json.loads(response.text)["item"]["lv1_tag_list"]
		category2=json.loads(response.text)["item"]["lv2_tag_list"]

		# content=json.loads(response.text)["summary"]
		# 文章分类：请输入一篇文章（含标题），为文章选择分类模块。
		return render_template('result_category.html', the_title='推荐分类',category=category,category2=category2,)
	return render_template('pushCategorry.html',the_title='文章分类',desction="请输入一篇文章（含标题），为文章选择分类模块.")

@app.route('/tag',methods=["GET","POST"])
def tag() -> 'html':
	if request.method=="POST":
		title=request.form.get("title")
		content=request.form.get("content")
		if title is   None or title=="":
			return render_template('pushCategorry.html', the_title='文章标签', desction="请输入一篇文章（含标题），生成文章核心内容标签。",msg="请输入标题")
		if content is   None or content=="":
			return render_template('pushCategorry.html', the_title='文章标签', desction="请输入一篇文章（含标题），生成文章核心内容标签。",msg="请输入标题")

		acccess_token=get_access_token()
		url="https://aip.baidubce.com/rpc/2.0/nlp/v1/keyword?charset=UTF-8&access_token="+acccess_token
		body={
			"title":title,
			"content": content,
		}
		Header={"Content-Type":"application/json"}
		response=requests.post(url,json=body,headers=Header)
		log_request(request,response.text)
		print(response.text)
		content=json.loads(response.text)["items"]
		return render_template('result_tag.html', the_title='文章标签',items=content)

	return render_template('pushCategorry.html',the_title='文章标签',desction="请输入一篇文章（含标题），生成文章核心内容标签。")


@app.route('/chat',methods=["GET","POST"])
def chat() -> 'html':
	if request.method=="POST":
		question=request.form.get("question")



		# # client_id 为官网获取的AK， client_secret 为官网获取的SK
		host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=eiBsX7AmncXIANL7yCGojkTA&client_secret=OnqEu2UEfSd6aPA7evwHYGg5EFRE0Tia'
		rq = urllib.request.Request(host)
		rq.add_header('Content-Type', 'application/json; charset=UTF-8')
		response = urllib.request.urlopen(rq)
		resp_taken = response.read()

		# if (resp_taken):
		#    print(resp_taken)

		text = json.loads(resp_taken)
		# print(text["access_token"])

		headers = {'Content-Type': 'application/json'}
		access_token = text["access_token"]
		url = 'https://aip.baidubce.com/rpc/2.0/unit/service/chat?access_token=' + access_token
		post_data = "{\"log_id\":\"UNITTEST_10000\",\"version\":\"2.0\",\"service_id\":\"S20837\",\"session_id\":\"\",\"request\":{\"query\":\""+question+"\",\"user_id\":\"88888\"},\"dialog_state\":{\"contexts\":{\"SYS_REMEMBERED_SKILLS\":[\"1057\"]}}}"
		rq = urllib.request.Request(url, data=post_data.encode('utf-8'), headers=headers)
		response = urllib.request.urlopen(rq)
		content = response.read().decode("utf-8")

		# if content:
		#    print(content)

		text1 = json.loads(content)
		log_request(request, content)

		content=text1['result']['response_list'][0]['action_list'][0]['say']
		return render_template('chat.html', the_title='小葵聊天机器人',items=content,question=question)

	return render_template('chat.html',the_title='小葵聊天机器人')

@app.route('/signup', methods=['GET', "POST"])
def signup_page():
	if request.method == "POST":
		user_name = request.form.get("username")
		password = request.form.get("password")
		user = User.query.filter(User.user_name == user_name).first()
		if user is not None:
			return render_template("signup.html", msg="该用户已经注册了")

		user = User(user_name=user_name, password=password)
		db.session.add(user)
		db.session.commit()
		return render_template('signup.html',signup=True)
	return render_template('signup.html')
@app.route('/login',methods=['POST',"GET"])
def login_page() -> 'html':
	if request.method=="POST":
		username = request.form.get("username")
		password = request.form.get("password")
		user = User.query.filter(User.user_name == username).first()

		if user is not None and user.password==password:
			log_request(request, user)
			return redirect("/index")
	return render_template('login.html',the_title ="向日葵语言识别系统")

@app.route('/index',methods=['GET'])
def xuanze() -> 'html':
	return render_template('index.html')
#

# 查看日志
@app.route('/viewlog')
def view_the_log() ->'html':
	with open('view.log',"r") as log:
		contents = []
		for line in log:
			contents.append([])
			for item in line.split('|'):
				contents[-1].append(escape(item))

	titles = ('Form data','Remote_addr','User_agent','results')
	return render_template('viewlog.html',
		the_title='View Log',
		the_row_titles=titles,
		the_data=contents,)


if __name__ == '__main__':
	app.run(debug=True)
